Daemon Thread in Java

(Tap the post to see more)


In Java, a daemon thread is a thread that runs in the background and does not prevent the Java Virtual Machine (JVM) from exiting when all non-daemon threads have completed their execution. Daemon threads are typically used for background tasks or services that can be terminated when the main application or other non-daemon threads finish their execution.

Example 01:

package com.java.Multi_threading;

public class DaemonThreadExample {

public static void main(String[] args) {

// Create a daemon thread

Thread daemonThread = new Thread(new DaemonTask());

// Set the thread as daemon

daemonThread.setDaemon(true);

// Start the daemon thread

daemonThread.start();

// Main thread sleeps for a while

try {

Thread.sleep(3000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("Main thread exiting. Daemon thread will be terminated.");

}

}


class DaemonTask implements Runnable {

@Override

public void run() {

while (true) {

System.out.println("Daemon thread is running...");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

← Back Next →

Comments

Popular posts from this blog

Wrapper Class

Information Security & Essential Terminology

Information Security Threat Categories